//
//  LCInputView.m
//  LCInputView
//
//  Created by Rochang on 2017/4/18.
//  Copyright © 2017年 Rochang. All rights reserved.
//

#import "LCInputView.h"

@interface LCInputView ()
@property (weak, nonatomic) IBOutlet UILabel *titleLabel;
@property (weak, nonatomic) IBOutlet UIView *tipView;
@property (weak, nonatomic) IBOutlet UITextField *textField;
@property(nonatomic, copy) cancelBlock cancel;
@property(nonatomic, copy) confirmBlock confirm;

@property (weak, nonatomic) IBOutlet UIButton *cancelButton;
@property (weak, nonatomic) IBOutlet UIButton *confirmButton;



@end

@implementation LCInputView

- (void)awakeFromNib {
    [super awakeFromNib];
    
    [self.cancelButton setTitle:Language(@"取消") forState:UIControlStateNormal];
    [self.confirmButton setTitle:Language(@"确定") forState:UIControlStateNormal];
    
    self.textField.keyboardType = UIKeyboardTypeASCIICapable;
}

+ (instancetype)shareInstance {
    static LCInputView *_instance;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        _instance = [[NSBundle mainBundle] loadNibNamed:NSStringFromClass([self class]) owner:nil options:nil].firstObject;
    });
    return _instance;
}

- (void)showWithTitle:(NSString *)title cancelBlock:(cancelBlock)cancel confirmBlock:(confirmBlock)confirm {
    self.cancel = cancel;
    self.confirm = confirm;
    self.textField.text = @"";
    self.titleLabel.text = title;
    self.tipView.layer.cornerRadius = 5;
    self.tipView.clipsToBounds = YES;
    [[UIApplication sharedApplication].keyWindow addSubview:self];
    self.frame = [UIScreen mainScreen].bounds;
    self.tipView.alpha = 0;
    self.alpha = 0;
    self.tipView.transform = CGAffineTransformMakeScale(0.1, 0.1);
    __weak typeof(self) weakSelf = self;
    [UIView animateWithDuration:0.2 animations:^{
        weakSelf.tipView.alpha = 1.0;
        weakSelf.alpha = 1.0;
        weakSelf.tipView.transform = CGAffineTransformIdentity;
    }];
    [self.textField becomeFirstResponder];
}

- (IBAction)cancel:(id)sender {
    if (self.cancel) {
        self.cancel();
    }
    [self hideWithAnimation:YES];
}

- (IBAction)confirm:(id)sender {
    if (self.confirm) {
        self.confirm(self.textField.text);
    }
    [self hideWithAnimation:YES];
}

- (void)hideWithAnimation:(BOOL)animtaion {
    if (!animtaion) {
        [self removeFromSuperview];
        return;
    }
    __weak typeof(self) weakSelf = self;
    [UIView animateWithDuration:0.2 animations:^{
        weakSelf.tipView.alpha = 0;
        weakSelf.alpha = 0;
        weakSelf.tipView.transform = CGAffineTransformMakeScale(0.1, 0.1);
    } completion:^(BOOL finished) {
        [weakSelf removeFromSuperview];
    }];
}

@end
